package LL8;

public class Main {
    //Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static class Solution {
        public ListNode partition(ListNode head, int x) {
            //1. 定义虚拟头结点与指针变量
            ListNode smallHead = new ListNode(-1);//较小值链表的虚拟头节点
            ListNode smallCur = smallHead; //较小值链表的操作指针变量

            ListNode largeHead = new ListNode(-1); //较大值链表的虚拟头节点
            ListNode largeCur = largeHead; //较大值链表的操作指针变量

            ListNode cur = head; //原链表的操作指针变量

            //2. 循环比较链表的节点值
            while (cur != null) {
                if (cur.val < x) {
                    smallCur.next = cur; //将当前节点衔接到较小值链表中
                    smallCur = cur; //移动操作节点指针变量

                } else {
                    largeCur.next = cur;//将当前节点衔接到较大值链表中
                    largeCur = cur; //移动操作节点指针变量

                }
                cur = cur.next;//移动当前操作节点的指针变量
            }

            //3. 处理较小值、较大值链表
            largeCur.next = null; //较大值组成的链表，末尾指向Null
            smallCur.next = largeHead.next; //衔接2个链表

            return smallHead.next; //返回链表：头节点为值较小的链表

        }
    }

    private static void printNode(ListNode head) {
        ListNode cur = head;
        //遍历每一个节点
        while (cur != null) {
            System.out.print(cur.val + "\t");
            cur = cur.next;//移动指针变量
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(4);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(2);
        printNode(head);

        Solution solution = new Solution();
        ListNode node = solution.partition(head, 3);
        printNode(node);
    }
}
